package br.usp.icmc.biomac.server;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URL;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author Babu Hussain
 * @version 0.5
 * 
 */
public class DicomRetrieve extends HttpServlet {
	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;

	@Override
	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		String wadoUrl = request.getParameter("wadourl");
		//System.out.println(wadoUrl);
		String modifiedWadoUrl = wadoUrl.replaceAll("-", "&");
//		String imageURL = modifiedWadoUrl.concat("&transferSyntax=1.2.840.100008.1.2&contentType=application/dicom");
		String imageURL = modifiedWadoUrl;//.concat("&transferSyntax=1.2.840.100008.1.2&contentType=application/dicom");
		InputStream resultInStream = null;
		OutputStream out = response.getOutputStream();
		try {
			int bytes_read;
			URL imageUrl = new URL(imageURL);
			resultInStream = imageUrl.openStream();
			byte[] buffer = new byte[4096];
			while ((bytes_read = resultInStream.read(buffer)) != -1)
				out.write(buffer, 0, bytes_read);
			out.flush();
			out.close();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	@Override
	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		doGet(request, response);
	}
}